/**
 * 
 */
package org.gas.barapraja.handler;

import org.gas.barapraja.db.entity.Message;
import org.gas.barapraja.handler.validator.MultiMessageValidator;
import org.gas.barapraja.proc.MsgStore;
import org.gas.barapraja.proc.PduProcessor;
import org.gas.barapraja.proc.TemporaryMsgStore;

import com.logica.smpp.pdu.SubmitMultiSM;
import com.logica.smpp.pdu.SubmitMultiSMResp;
import com.logica.smpp.pdu.WrongLengthOfStringException;

/**
 * @author gilang
 *
 */
public class MultiMsgRequestHandler extends GasHandlerAdapter {

	private MsgStore msgStore;

	private MultiMessageValidator validator;

	private static MultiMsgComposer composer;

	/**
	 * 
	 * @param pduProcessor
	 */
	public MultiMsgRequestHandler(PduProcessor pduProcessor) {
		setPduProcessor(pduProcessor);
		msgStore=TemporaryMsgStore.getInstance();
		validator=new MultiMessageValidator();
		composer=new MultiMsgComposer();
	}

	/* (non-Javadoc)
	 * @see org.gas.barapraja.handler.GasHandlerAdapter#handleRequest(com.logica.smpp.pdu.SubmitMultiSM)
	 */
	@Override
	public int handleRequest(SubmitMultiSM multiSM) {
		int status=validator.validate(multiSM);
		try{
			if(status==GasValidatorAdapter.TOKEN_OK){
				Message[] messages=composer.compose(multiSM, validator.getNumOfMsg());
				for(int i=0;i<messages.length;i++){
					msgStore.addMsg(messages[i]);
				}
			}
			SubmitMultiSMResp multiSMResp=(SubmitMultiSMResp)multiSM.getResponse();
			multiSMResp.setMessageId(String.valueOf(validator.getNumOfMsg()));
			pduProcessor.serverResponse(multiSMResp);
		}catch (WrongLengthOfStringException e) {
			e.printStackTrace();
		}
		return status;
	}



}

class MultiMsgComposer{

	public Message[] compose(SubmitMultiSM multiSM,int size){
		Message[] messages=new Message[size];
		for(int i=0;i<size;i++){
			messages[i]=new Message();
			messages[i].setSource(multiSM.getSourceAddr().getAddress());
			messages[i].setTarget(multiSM.getDestAddress(i).getAddress().getAddress());
			messages[i].setContent(multiSM.getShortMessage());
		}
		return messages;
	}
}